package cn.chia.front.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.chia.pojo.Orderitems;
import cn.chia.pojo.Orders;
import cn.chia.pojo.Ordertime;
import cn.chia.pojo.TblActivity;
import cn.chia.pojo.TblGroupPurchase;
import cn.chia.pojo.TblItems;
import cn.chia.pojo.TblShopcar;
import cn.chia.pojo.User;
import cn.chia.service.IActivityService;
import cn.chia.service.IGroupPurService;
import cn.chia.service.IItemService;
import cn.chia.service.IShopcarService;
import cn.chia.service.OrderService;
import cn.chia.service.OrdertimeService;
import cn.chia.utils.FullCount;
import cn.chia.utils.FullCountUtil;
import cn.chia.utils.UUIDUtil;

import com.opensymphony.xwork2.ActionSupport;


@Controller
@Scope(value="prototype")
public class ShopAction extends ActionSupport{

	/**李胜
	 * 购物车的action，业务逻辑的实现
	 */
	private static final long serialVersionUID = 1L;

	private IShopcarService iShopcarService;
	private IItemService iItemService;
	private IActivityService iActivityService;
	private OrderService orderService;
	private OrdertimeService ordertimeService;
	private IGroupPurService groupPurServiceImpl;
	private String sid;//购物车id
	private String tid;//商品id
	private String[] num;//提交订单时商品的数量
	private List<TblShopcar> slist;//查询购物车的表
	private String addr;//订单中的地址（配送货物地址）
	private String phone;//联系人电话
	private String words;//买家留言
	private String paystate;//付款方式
	private Orders order;
	private Set set;
	private String orderNumber;
	private Date psday;//配送日期
	private String pstime;//配送时间
	private String gid;//拼单主键
	private String receivername;//shouhuoren
	
	
	private List<Orderitems> orderItemsList;
	User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
	//增加购物车
	public String addShopcar() throws Exception{
		System.out.println("========ADD中的tid："+tid);
		TblItems items =  iItemService.findById(tid);
		TblShopcar shopcar = new TblShopcar();
			shopcar.setDate(new Date());
			shopcar.setNum(1);
			shopcar.setUser(user);
			shopcar.setTblItems(items);
		iShopcarService.insert(shopcar);
		String result = iShopcarService.findAll(user).size()+"";
		
		ServletActionContext.getResponse().getWriter().print(result);
        
        
		return null;
	}
	
	//删除购物车
	public String delShopcar() throws Exception{
		System.out.println("进入删除购物车方法。。。。。。。。。");
		iShopcarService.delete(Integer.parseInt(sid));
		return SUCCESS;
	}
	
	//查询购物车
	public String queryShopcar() throws Exception{
		slist = iShopcarService.findAll(user);
		System.out.println("list中的商品数量为......"+slist.size());
		return SUCCESS;
	}
	
	//生成订单
	public String toOrder() throws Exception{
		
		String orderNumber = UUIDUtil.getUUID();
		System.out.println("orderNumber:"+orderNumber);
		//购物车中的每个商品的活动id和每个商品总价的list，该list用于传到工具类中计算
		List<FullCount> zonglist = new ArrayList<FullCount>();
		//购物车中商品对应的分类活动满减；该list为工具类返回的，中有活动id和能参与该活动的商品的总价
		List<FullCount> avtplist = new ArrayList<FullCount>();
		//总价
		Double totalall = 0.0;
		//单品打折优惠的总数目
		Double zhe = 0.0;
		//满减优惠的总数目
		Double man = 0.0;
		//优惠后的总价
		Double total = 0.0;
		//获取购物车中的所有商品
		slist = iShopcarService.findAll(user);
		//把用户购买的商品个数对应起来(同时计算出totalall和zhe)
		for (int i = 0; i < slist.size(); i++) {
			FullCount fullCount = new FullCount();
			slist.get(i).setNum(Integer.parseInt(num[i]));
			TblShopcar shopcar = slist.get(i);
			totalall += shopcar.getTblItems().getRetailPrice()*shopcar.getNum();
			zhe += shopcar.getTblItems().getRetailPrice()*shopcar.getNum()*(1-shopcar.getTblItems().getTblActivity().getDiscount());
			fullCount.setAvid(shopcar.getTblItems().getTblActivity().getActivityId());
			fullCount.setCount(shopcar.getTblItems().getRetailPrice()*shopcar.getNum()*shopcar.getTblItems().getTblActivity().getDiscount());
			zonglist.add(fullCount);
		}
		total = totalall - zhe;
		
		//得到活动id和能参与该活动的商品的总价的list
		avtplist = FullCountUtil.qCTG(zonglist);
		for (int i = 0; i < avtplist.size(); i++) {
			TblActivity activity = iActivityService.findById(avtplist.get(i).getAvid());
			if (avtplist.get(i).getCount() >= activity.getFullCount()) {
				man += activity.getSubstractCount();
				total -= activity.getSubstractCount();
			}
		}
		
		Ordertime ordertime = new Ordertime();
			ordertime.setOrdernumber(orderNumber);
			ordertime.setBuildtime(new Date());
			ordertimeService.add(ordertime);
		
		Orders orders = new Orders();
			orders.setAddr(addr);
			orders.setFlag(1);
			orders.setOrderNumber(orderNumber);
			orders.setOrdertime(ordertimeService.findById(orderNumber));
				String pay = "";
				if (paystate.equals("-1")) {
					pay = "微信支付";
				}else if(paystate.equals("1")){
					pay = "支付宝";
				}else{
					pay = "余额支付";
				}
			
			if(pstime.equals("1")){
				orders.setUszdtime("立即配送");
				total+=6;
			}else{
				orders.setUszdtime("配送时间：下午  13:00~16:00");
			}
			orders.setPaystate(pay);
			orders.setPhone(phone);
			orders.setUszdday(psday);
			orders.setState("未付款");
			orders.setTotal(total);
			orders.setInmanage(0);
			orders.setUser(user);
			orders.setWords(words);
			orders.setReceivername(receivername);
			System.out.println("***************8收货人姓名************"+receivername);
			orderService.add(orders);
			
			//把用户购买的商品个数对应起来(同时计算出totalall和zhe),这里用来把数据存到订单明细中，必须有了订单才能存订单明细
			for (int i = 0; i < slist.size(); i++) {
				slist.get(i).setNum(Integer.parseInt(num[i]));
				TblShopcar shopcar = slist.get(i);
				Orderitems orderitems = new Orderitems();
					orderitems.setCount(Integer.parseInt(num[i]));
					orderitems.setItemname(shopcar.getTblItems().getItemName());
					String itempic = shopcar.getTblItems().getItemPic().split(",")[1];
					
					orderitems.setItempic(shopcar.getTblItems().getItemPic());
					
					orderitems.setSubtotal(shopcar.getTblItems().getRetailPrice()*shopcar.getNum());
					orderitems.setTblItems(shopcar.getTblItems());
					System.out.println("orderNumber:"+orderNumber);
					orderitems.setOrders(orderService.findByNumber(orderNumber));
					orderService.addOrderItems(orderitems);
				iShopcarService.delete(shopcar.getShopcarId());
			}
			ServletActionContext.getRequest().getSession().setAttribute("orderNumber", orderNumber);
			
		return "order";
	}
	//转到拼单购物车页面
	public String goPinShopcar(){
		ServletActionContext.getRequest().getSession().setAttribute("gid", gid);
		return SUCCESS;
	}
	//生成拼单的订单
	public String pinOrder() throws Exception{
		String orderNumber = UUIDUtil.getUUID();
		Ordertime orderTime = new Ordertime();
			orderTime.setOrdernumber(orderNumber);
			orderTime.setBuildtime(new Date());
			ordertimeService.add(orderTime);
		
		TblGroupPurchase groupPurchase = groupPurServiceImpl.findGroupById(Integer.parseInt(gid));
			
		Orders orders = new Orders();
			orders.setOrderNumber(orderNumber);
			orders.setFlag(2);
			orders.setInmanage(0);
			orders.setAddr(addr);
			
			String pay = "";
			if (paystate.equals("-1")) {
				pay = "微信支付";
			}else if(paystate.equals("0")){
				pay = "支付宝";
			}else{
				pay = "余额支付";
			}
			orders.setPhone(phone);
			orders.setState("未付款");
			orders.setUser(user);
			orders.setPaystate(pay);
			if (words != null) {
				orders.setWords(words);
			}
			orders.setUszdday(psday);
			orders.setReceivername(receivername);
			orders.setUszdtime("下午 13:00~16:00");
			orders.setPinId(groupPurchase);
			orders.setTotal(groupPurchase.getNowPrice()*1.0);
			orders.setOrdertime(ordertimeService.findById(orderNumber));
			
			orderService.add(orders);
			ServletActionContext.getRequest().getSession().setAttribute("orderNumber", orderNumber);
		return SUCCESS;
	}
	
	
	public String listorderitems() throws Exception{
		System.out.println();
		orderNumber = (String) ServletActionContext.getRequest().getSession().getAttribute("orderNumber");
		order = orderService.findByNumber(orderNumber);
		System.out.println(order.toString());
		
		set = order.getOrderitemses();
		System.out.println("*******下面输出的是set里的东西*********");
		System.out.println("set集合的大小: " + set.size());
		List<Orderitems> orderItemsList = iShopcarService.findAllOrderitems(order.getOid());
		ServletActionContext.getRequest().setAttribute("orderItemsList", orderItemsList);
		for(int i=0; i<orderItemsList.size(); i++){
			System.out.println(orderItemsList.get(i).getItemname());
		}
		System.out.println(set.toString());
		return "success";
	}
	
	
	
	
	
	
	
	
	
	
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getTid() {
		return tid;
	}
	public void setTid(String tid) {
		this.tid = tid;
	}
	public String[] getNum() {
		return num;
	}
	public void setNum(String[] num) {
		this.num = num;
	}
	public List<TblShopcar> getSlist() {
		return slist;
	}
	public void setSlist(List<TblShopcar> slist) {
		this.slist = slist;
	}
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getWords() {
		return words;
	}
	public void setWords(String words) {
		this.words = words;
	}
	
	public String getPaystate() {
		return paystate;
	}

	public void setPaystate(String paystate) {
		this.paystate = paystate;
	}

	public Orders getOrder() {
		return order;
	}

	public void setOrder(Orders order) {
		this.order = order;
	}

	public Set getSet() {
		return set;
	}

	public void setSet(Set set) {
		this.set = set;
	}

	@Resource(name="shopcarServiceImpl")
	public void setiShopcarService(IShopcarService iShopcarService) {
		this.iShopcarService = iShopcarService;
	}
	
	@Resource(name="itemServiceImpl")
	public void setiItemService(IItemService iItemService) {
		this.iItemService = iItemService;
	}
	
	@Resource(name="activityServiceImpl")
	public void setiActivityService(IActivityService iActivityService) {
		this.iActivityService = iActivityService;
	}
	@Resource(name="orderServiceImpl")
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	@Resource(name="ordertimeServiceImpl")
	public void setOrdertimeService(OrdertimeService ordertimeService) {
		this.ordertimeService = ordertimeService;
	}

	@Resource(name="groupPurServiceImpl")
	public void setGroupPurServiceImpl(IGroupPurService groupPurServiceImpl) {
		this.groupPurServiceImpl = groupPurServiceImpl;
	}
	public List<Orderitems> getOrderItemsList() {
		return orderItemsList;
	}

	public void setOrderItemsList(List<Orderitems> orderItemsList) {
		this.orderItemsList = orderItemsList;
	}

	public String getOrderNumber() {
		return orderNumber;
	}

	public void setOrderNumber(String orderNumber) {
		this.orderNumber = orderNumber;
	}

	public Date getPsday() {
		return psday;
	}

	public void setPsday(Date psday) {
		this.psday = psday;
	}

	public String getPstime() {
		return pstime;
	}

	public void setPstime(String pstime) {
		this.pstime = pstime;
	}

	public String getGid() {
		return gid;
	}

	public void setGid(String gid) {
		this.gid = gid;
	}

	public String getReceivername() {
		return receivername;
	}

	public void setReceivername(String receivername) {
		this.receivername = receivername;
	}

	
	
	
	
}
